import { keepPreviousData, useMutation, useQueries, useQuery } from "@tanstack/react-query";
import { Avatar, Badge, Button, message, Modal, Space, Table } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react"
import { getRoleUserList, saveRoleUser } from '@/api/system/user'
import SearchForm from "@/components/searchForm";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import {
  delRoleUser
} from '@/api/system/role'
import SelectUserModal from "../../user/modules/selectUserModal";

const colorList = ['#F38709', '#813AFD', '#00C4AA', '#4B7AEE']
const queryItems = [
  {
    name: 'userNameOrName',
    label: '编码或名称',
    type: 'INPUT',
  }
];

const RoleDetailModal = forwardRef((_, ref) => {
  const selectUserModalRef = useRef()
  const [roleId, setRoleId] = useState()
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [queryParam, setQueryParam] = useState({});
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const [isModalOpen, setIsModalOpen] = useState(false);
  useDictionary(['user_status'])

  const confirm = Modal.confirm;
  const columns = [
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (text, _, idx) => (<>
        <Space size={8}>
          <Avatar shape="square" style={{ backgroundColor: colorList[idx % 4] }}>
            {text.slice(0, 2)}
          </Avatar>
          {text}
        </Space>
      </>)
    },
    {
      title: '组织',
      dataIndex: 'deptName',
    },
    {
      title: '用户状态',
      dataIndex: 'status',
      align: 'center',
      render: (text) => (<Badge status={text == '0' ? 'processing' : 'error'} text={<DisplayLabel value={text} type="user_status" />} />)
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '100px',
      render: (_, record) => <a onClick={() => { deleteConfirm(record) }}>删除</a>,
    },
  ];
  const { data: tableData, isFetching, isPending, refetch } = useQuery({
    queryKey: ['getRoleUserList', roleId, queryParam, page,],
    queryFn: () => {
      return getRoleUserList({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        roleId: roleId,
        ...queryParam,
      }).then((res) => {
        return res.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
    enabled: !!roleId,
  })


  useImperativeHandle(ref, () => ({
    showModal: (id) => {
      setQueryParam({})
      setRoleId(id)
      setIsModalOpen(true)
    },
  }));

  const mutation = useMutation({
    mutationFn: (param) => {
      return appModelApi(param)
    },
    onSuccess: () => {
      setIsModalOpen(false)
    }
  })

  const handleOk = () => {
    setIsModalOpen(false)
    // mutation.mutate({ resourceIds: traverseTree(checked), roleId })
  };
  const handleCancel = () => {
    setIsModalOpen(false)
  };

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const deleteConfirm = (row) => {
    const ids = row.id || selectedRowKeys
    const userNames = row.name || selectedRows.map(d => d.name)
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      content: '当前选中编号为' + userNames + '的数据',
      autoFocusButton: null,
      onOk() {
        return delRoleUser(roleId, ids)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  const onSelectUser = async (rows) => {
    const saveRoleUserForm = {
      userId: rows.map(d => d.id).join(';'),
      roleId: roleId
    }
    return saveRoleUser(saveRoleUserForm).then((res) => {
      if (res.code !== 200) return false
      message.success('添加成功')
      refetch()
      return true
    })
  }

  return <Modal width={'80%'} loading={isPending} title="权限管理" open={isModalOpen} confirmLoading={mutation.isPending} onOk={handleOk} onCancel={handleCancel}>
    <SearchForm
      onSearch={(values) => setQueryParam({ ...values })}
      items={queryItems}
      searchContent="查询"
      showReset={false}
      buttons={<>
        <Button icon={<PlusOutlined />} type="primary" onClick={() => selectUserModalRef.current.showModal()}>添加用户</Button>
        {selectedRowKeys.length > 0 && <Button danger onClick={deleteConfirm}>删除</Button>}
      </>}
    />
    <div style={{ marginTop: '20px' }}>
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.list}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}
      />
    </div>

    <SelectUserModal ref={selectUserModalRef} onOk={onSelectUser} />
  </Modal>
})

export default RoleDetailModal